package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"order_srv/model/mysql"
	"order_srv/pkg"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *order.OrderAddRequest) (*order.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	var good = mysql.Goods{}
	err := good.Find(int(in.GoodsId))
	if err != nil {
		return nil, err
	}
	if good.ID == 0 {
		logx.Error("没找到该商品")
		return nil, fmt.Errorf("下单失败")
	}
	OrderSn := uuid.NewString()
	var o = mysql.Order{
		UserId:  in.UserId,
		OrderSn: OrderSn,
		Amount:  float64(in.Num) * good.Price,
		Starts:  "2",
		Payment: "1",
	}
	var og = mysql.OrderGoods{
		OrderId: int64(o.ID),
		GoodsId: in.GoodsId,
		Title:   good.Title,
		Price:   good.Price,
		Cover:   good.Cover,
		Stock:   good.Stock,
		Starts:  good.Starts,
	}
	err = mysql.CreateAnimals(&o, &og)
	if err != nil {
		return nil, err
	}

	return &order.OrderAddResponse{OrdersId: int64(o.ID), Url: pkg.Alipay()}, nil
}
